import mongoose from 'mongoose';
import {GlobalVariable} from "../GlobalVariable";
import {logUtil} from "../log/LogUtil";
import {ELevel} from "../log/ILogUtil";
import {IKeyValue} from "../core/CpcInterface";
import {ModelUtil} from "./ModelUtil";
import {RouterCtrl} from "../routes/RouterCtrl";

let {user, pass, host, port, database} = GlobalVariable.envConfig.mongodb_config;
let uri = "";
if (user && pass) {
    // mongodb://user:pass@localhost:port/database
    // mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb
    uri = `mongodb://${user}:${pass}@${host}:${port}/?authSource=admin`;
} else {
    uri = `mongodb://${host}:${port}/${database}`;
}
console.log("数据库地址:" + uri);
console.log("数据库连接中...");
mongoose.connect(uri).then(async res => {
    logUtil.log(ELevel.info, '数据库连接成功');
    const count = await addAllRouter();
    logUtil.log(ELevel.info, '所有项目路由添加完毕,添加个数:' + count);
}).catch(error => {
    console.error("连接失败", error);
    logUtil.log(ELevel.error, '连接数据库失败' + error.message);
});

async function addAllRouter() {
    let count = 0;
    const projects = await ModelUtil.project.aggregate([
        {
            $lookup: {
                from: 'router',  // 关联的集合
                localField: 'id',  // 本地关联的字段
                foreignField: 'projectId',  // 对方集合关联的字段
                as: 'routers',  // 结果字段名,
            },
        }
    ]);
    for (let project of projects) {
        if (project.disable) {
            continue;
        }
        let projectPath = project.path;
        for (const router of project.routers) {
            if (router.disable) {
                continue;
            }
            const {method, path, handler} = router;
            const res = RouterCtrl.add(GlobalVariable.router, projectPath + path, method, handler);
            if (res.code !== 200) {
                logUtil.log(ELevel.error, JSON.stringify(res));
            } else {
                count++;
            }
        }
    }
    return count;
}